package cn.yilongquan.Interceptor;


import cn.yilongquan.util.JwtUtil;
import cn.yilongquan.util.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("token");  //56d96a2-1e9f-4e7a-a34b-1071a81cd9bf
        //2.获取登录信息
        if(token!=null){
            try {
                Payload payload = JwtUtil.parseJwtToken(token);
                return true; //放行 - 没有做刷新过期时间
            } catch (Exception e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
                return false;
            }
            //3.2.不为null=登录了=>放行
        }
        //3.1.为null=没有登录或过期了=>想办法跳转登录页面
        //response.sendRedirect("http://localhost:8081/#/login"); - 万一是用户访问
        //告诉浏览器我要给你响应一个json数据[自动将json格式的字符串-json对象]
        return true;
    }
}